package net.pimpas.web.jsf.page.navigation;

import java.util.Collection;

import javax.servlet.ServletContextEvent;

import net.pimpas.operation.exception.OperationException;
import net.pimpas.operation.operation.OperationAbstract;
import net.pimpas.operation.operation.OperationAnnotation;
import net.pimpas.web.jsf.page.controller.PageControl;
import net.pimpas.web.jsf.page.controller.PageController;

import org.apache.myfaces.config.RuntimeConfig;
import org.apache.myfaces.context.servlet.ServletExternalContextImpl;

@OperationAnnotation(name="ProcessNavigationRules")
public class ProcessNavigationRulesOperation extends OperationAbstract<Object>{
	
	private ServletContextEvent context;
	private Collection<Class<? extends PageController>> navigations;
	
	@SuppressWarnings("unchecked")
	@Override
	public void init(Object... arg0) throws OperationException {
		this.setContext((ServletContextEvent) arg0[0]);
		this.setNavigations((Collection<Class<? extends PageController>>) arg0[1]);
	}
	
	@Override
	public Object call() throws Exception {
		RuntimeConfig runtime = RuntimeConfig.getCurrentInstance(new ServletExternalContextImpl(this.getContext().getServletContext(), null, null));
		org.apache.myfaces.config.impl.digester.elements.NavigationRule rule = null;
		org.apache.myfaces.config.impl.digester.elements.NavigationCase nc = null;
		NavigationRule nr = null;
		PageControl control = null;
		for(Class<? extends PageController> clazz: this.getNavigations()) {
			control = (PageControl)clazz.getAnnotation(PageControl.class);
			nr = control.navigationRule();
			rule = new org.apache.myfaces.config.impl.digester.elements.NavigationRule();
			rule.setFromViewId(control.pageUri()+".jsp");
			for(NavigationCase c: nr.cases()) {
				nc = new org.apache.myfaces.config.impl.digester.elements.NavigationCase();
				nc.setFromOutcome(c.fromOutcome());
				nc.setToViewId(c.toViewId()+".jsp");
				
				rule.addNavigationCase(nc);
			}
			runtime.addNavigationRule(rule);
		}
		
		return null;
	}

	public ServletContextEvent getContext() {
		return context;
	}

	public void setContext(ServletContextEvent context) {
		this.context = context;
	}

	public Collection<Class<? extends PageController>> getNavigations() {
		return navigations;
	}

	public void setNavigations(Collection<Class<? extends PageController>> navigations) {
		this.navigations = navigations;
	}
}